<template>
  <div class="procure-outbound-put">
    <div class="info">
      <div>
        <div class="left">
          <p class="creater mr40">制单人：{{ userInfo.createBy || "-" }}</p>
          <p class="mr40">制单时间：{{ userInfo.createTime || "-" }}</p>
          <p class="mr40">出库单号：{{ userInfo.deliveryNo || "-" }}</p>
        </div>
        <div class="right">
          <el-button type="info" plain @click="$router.go(-1)">返回</el-button>
        </div>
      </div>
    </div>

    <el-container class="content">
      <el-aside>
        <header>
          <div class="supper">
            <p>
              出库仓：<b>{{ $route.query.warehouseName }}</b>
            </p>
          </div>
          <div class="count">
            <h3>合计</h3>
            <p>预计出库数量：{{ COUNT.yNum1 }}</p>
            <p>预计出库件数：{{ COUNT.yNum2 }}</p>
            <p>实际出库数量：{{ COUNT.sNum1 }}</p>
            <p>实际出库件数：{{ COUNT.sNum2 }}</p>
          </div>
        </header>

        <!-- 商品列表 -->
        <div class="products-list">
          <div class="table-header">
            <div>
              <div>
                <div class="col1">商品信息</div>
                <div class="col2">数量</div>
                <div class="col3">预计出库件数</div>
                <div class="col4">单位</div>
                <div class="col5">实际出库数量</div>
                <div class="col6">实际出库件数</div>
                <div class="col7">仓库</div>
              </div>
            </div>
          </div>

          <div class="table-body" v-if="list.length > 0">
            <div class="list-item" v-for="(item, index) in list" :key="index">
              <div>
                <div class="col1">
                  <div>
                    <div class="left">
                      <img :src="item.mainPicUrl" alt="" />
                    </div>
                    <div class="right">
                      <h3 class="name text-break">{{ item.productAliasName || "-" }}</h3>
                      <p style="white-space: break-spaces">
                        <!-- {{ getSpes(item.skuSpecification) }} -->
                        {{ item.skuSpecification }}
                      </p>
                      <p>SKU编码：{{ item.skuCode || "-" }}</p>
                      <p>ID:{{ item.warehouseProductsId || "-" }}</p>
                    </div>
                  </div>
                </div>
                <div class="col2">
                  {{ item.canDeliveryNum || "-" }}
                  <!-- <el-input-number
                    :min="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.canDeliveryNum  "
                    oninput="value=value.replace(/[^0-9]/g, '')"
                  ></el-input-number> -->
                </div>
                <div class="col3">
                  {{ item.canDeliveryPartNum || "-" }}
                  <!-- <el-input-number
                    :min="0" :precision="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.deliveryPartQuantity"
                    oninput="value=value.replace(/[^0-9]/g, '')"
                  ></el-input-number> -->
                </div>
                <div class="col4">
                  {{ getName(item.productUnit) || "-" }}
                  <!-- {{ item.productUnit || "-" }} -->
                </div>
                <div class="col5">
                  <el-input-number
                    :min="1"
                    :max="item.canDeliveryNum || 1"
                    :precision="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.quantity"
                    @change="
                      val => {
                        // item.partQuantity = item.partNum * Number(val);
                      }
                    "
                    @keydown="channelInputLimit"
                  ></el-input-number>
                </div>
                <div class="col6">
                  <!-- {{ item.partQuantity || "-" }} -->
                  <el-input-number
                    :min="0"
                    :max="item.canDeliveryPartNum || 0"
                    :precision="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.partQuantity"
                    @keydown="channelInputLimit"
                  ></el-input-number>
                </div>
                <div class="col7">{{ item.warehouseName || "-" }}</div>
              </div>
              <div class="tips">
                <p class="label">备注</p>
                <!-- <el-input maxlength="200" v-model="item.remark" placeholder="请输入"></el-input> -->
                <RemarkEditor v-model="item.remark" />
              </div>
            </div>
          </div>
          <div v-else style="display: flex; justify-content: center; width: 100%">
            <el-empty description="暂无数据" />
          </div>
        </div>
      </el-aside>
      <el-main width="300px">
        <!-- 用户信息---只有是订单出库单才显示 -->
        <div class="sh-info">
          <p>用户信息</p>
          <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 600px">
            <el-form-item label="姓名">
              <span>{{ detail.customerName || "-" }}</span>
            </el-form-item>
            <el-form-item label="电话">
              <span>{{ detail.customerMobileCode || "-" }}</span>
            </el-form-item>
          </el-form>
        </div>
        <div class="ck-time mb20">
          <p>期望出库日期</p>
          <el-date-picker
            v-model="expectStockTime"
            value-format="YYYY-MM-DD  HH:mm:ss"
            type="datetime"
            placeholder="请选择"
            style="width: 100%"
          />
        </div>
        <div class="divider"></div>

        <!-- 关联借调客户信息 -->
        <SecondCustomer ref="secondCustomerRef" />
        <div class="divider"></div>

        <!-- 收货信息 -->
        <div class="sh-info">
          <p class="sh-address">
            <span>收货信息</span>
            <el-button
              type="primary"
              link
              size="small"
              @click="
                () => {
                  optionInfo.customerId = detail.customerId;
                  optionInfo.selectedObj = {
                    receivingAddressId: form.receivingAddressId,
                    receivingName: form.receivingName,
                    receivingMobile: form.receivingMobile,
                    receivingAreaIds: String(form.receivingAreaIds),
                    receivingAddress: form.receivingAddress
                  };
                  optionInfo.customerId = detail.customerId;
                  optionInfo.isShow = true;
                }
              "
              >地址管理</el-button
            >
          </p>
          <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 600px" disabled>
            <el-form-item
              label="收货人"
              prop="receivingName"
              :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
            >
              <el-input v-model="form.receivingName" placeholder="请输入" />
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="receivingMobile"
              :rules="[
                { required: true, message: '请输入' },
                { pattern: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
              ]"
            >
              <el-input v-model="form.receivingMobile" placeholder="请输入" />
            </el-form-item>
            <el-form-item
              prop="receivingAreaIds"
              label="收货地址"
              :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
            >
              <el-cascader
                placeholder="请选择"
                class="pb10"
                ref="cascaderRef"
                v-model="form.receivingAreaIds"
                :options="mapList"
                :props="{
                  expandTrigger: 'hover', //次级菜单的展开方式
                  label: 'name',
                  value: 'id'
                }"
                @change="handleChange"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item
              prop="receivingAddress"
              label="详细地址"
              :rules="{ required: true, message: '请输入', trigger: ['blur', 'change'] }"
            >
              <el-input
                v-model="form.receivingAddress"
                placeholder="请输入"
                oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="divider"></div>

        <!-- 入库备注 -->
        <div class="ck-tips">
          <p class="label">出库备注</p>
          <!-- <el-input maxlength="200" v-model="textarea" :rows="10" type="textarea" placeholder="请输入" /> -->
          <RemarkEditor v-model="textarea" />
        </div>
      </el-main>
    </el-container>

    <!-- 操作按钮栏 -->
    <div class="action-wrap">
      <!-- <el-button type="info" plain>取消</el-button> -->
      <el-button type="primary" @click="submit">提交出库单</el-button>
    </div>

    <!-- 确认暂存的list会清空 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenClear"
      :message="'您正在重新选择出库仓，当前商品信息将被重置，重新添加商品，请问是否继续当前操作？'"
      :submitBtnText="'继续前往'"
      @submit="returnSubmitClear"
    />

    <!-- 新建配送人 -->
    <el-dialog
      v-model="dialogVisible"
      :title="'新建配送人'"
      width="500"
      align-center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeAdd"
    >
      <div class="form-wrap">
        <el-form :model="form2" ref="form2Ref" label-width="auto" style="max-width: 600px">
          <el-form-item prop="warehouseName" label="配送人名" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
            <el-input
              v-model="form2.warehouseName"
              placeholder="请输入"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item
            prop="managePhoneNo"
            label="手机号"
            :rules="[
              { required: true, message: '请输入', trigger: ['blur'] },
              { pattern: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
          >
            <el-input
              v-model="form2.managePhoneNo"
              placeholder="请输入"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button @click="closeAdd">取消</el-button>
          <el-button type="primary" @click="addSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地址管理 -->
    <addressManage :optionInfo="optionInfo" @close="closeAddress" @submit="submitAddress" />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import { getSuppliers } from "@/apis/products/specifications";
import moment from "moment";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import { getTempDeliveryProductList, createDeliveryOrder } from "@/apis/procure/indent-outbound";
import { ListPage } from "@/apis/procure/warehouse";
import { ElMessage, ElMessageBox } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import china from "@/utils/china.json";
import addressManage from "@/views/procure/outbound/components/addressManage";
import { createOtherDeliveryOrderInfo } from "@/apis/procure/outbound";
import { channelInputLimit } from "@/utils";
import RemarkEditor from "@/components/RemarkEditor";
import SecondCustomer from "@/views/procure/outbound/components/secondCustomer.vue";

const secondCustomerRef = ref();
const houseList = ref([]); //出库仓下拉数据
const houseValue = ref(""); //选中的出库仓
const list = ref([]);
const detail = ref({});
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const storeList = ref([]); //收货仓库下拉数据
const expectStockTime = ref(""); //期望出库时间
const textarea = ref("");
const userInfo = ref({});
const _isOpenClear = ref(false);
const psList = ref([{ label: "配送人A", value: 1 }]); //配送人员下拉数据
const psValue = ref(null); //选中的配送人员
const form = ref({}); //收货信息表单数据
const formRef = ref();
const form2 = ref({}); //新建配送人表单数据
const form2Ref = ref();
const mapList = ref(china);
const dialogVisible = ref(false);
const optionInfo = ref({ isShow: false }); //地址管理弹窗
const COUNT = ref({ yNum1: 0, yNum2: 0, sNum1: 0, sNum2: 0 });

onMounted(async () => {
  const res = await getSuppliers();
  houseList.value = res.data;

  const info = await createOtherDeliveryOrderInfo();
  userInfo.value = info.data;
  // userInfo.value = {
  //   name: JSON.parse(localStorage.getItem("userinfo")).tenantName,
  //   time: moment().format("YYYY/MM/DD HH:mm:ss")
  // };

  const res2 = await ListPage({ page: 1, size: 9999 }); //入库仓
  storeList.value = res2.data.records;

  getList();
});

watch(
  () => list.value,
  val => {
    COUNT.value = { yNum1: 0, yNum2: 0, sNum1: 0, sNum2: 0 };
    for (let item of val) {
      COUNT.value.yNum1 += Number(item.canDeliveryNum);
      COUNT.value.yNum1 += Number(item.canDeliveryPartNum);
      COUNT.value.sNum1 += Number(item.quantity);
      COUNT.value.sNum2 += Number(item.partQuantity);
    }
  },
  { deep: true }
);

//关闭地址管理弹窗
const closeAddress = () => {
  optionInfo.value.isShow = false;
};
//地址管理submit回调
const submitAddress = selectObj => {
  optionInfo.value.isShow = false;
  // console.log("选中的地址===", selectObj);

  form.value = {
    receivingAddressId: selectObj.receivingAddressId,
    receivingName: selectObj.receivingName,
    receivingMobile: selectObj.receivingMobile,
    receivingAreaIds: selectObj.receivingAreaIds ? selectObj.receivingAreaIds.split(",").map(Number) : [],
    receivingAddress: selectObj.receivingAddress
  };
};

//打开新建配送人弹窗
const openAdd = () => {
  dialogVisible.value = true;
};
//关闭新建配送人弹窗
const closeAdd = () => {
  form2Ref.value.resetFields();
  dialogVisible.value = false;
};

//确认新建配送人
const addSubmit = () => {
  form2Ref.value.validate((valid, fields) => {
    if (valid) {
      closeAdd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const cascaderRef = ref();
const handleChange = value => {
  console.log("producerList", value);
  // const nodes = cascaderRef.value.getCheckedNodes();
  // console.log("找到了当前选中的节点数据===", nodes);
  // form.value.provinceId = nodes[0].pathValues[0];
  // form.value.cityId = nodes[0].pathValues[1];
  // form.value.districtId = nodes[0].pathValues[2];
  // form.value.provinceName = nodes[0].pathLabels[0];
  // form.value.cityName = nodes[0].pathLabels[1];
  // form.value.districtName = nodes[0].pathLabels[2];
};

const toPath = () => {
  if (route.query._time && houseValue.value === route.query.factoryId) {
    router.push({
      path: "/procure/outbound/select-prod",
      query: { factoryId: houseValue.value, _time: route.query._time }
    });
  } else {
    _isOpenClear.value = true;
  }
};
const returnSubmitClear = () => {
  router.push({
    path: "/procure/outbound/select-prod",
    query: { factoryId: houseValue.value, _time: new Date().getTime() }
  });
};

const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

//确认创建出库单
const submit = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      const jdInfo = secondCustomerRef.value.getData();
      const params = {
        ...form.value,
        receivingAreaIds: String(form.value.receivingAreaIds),
        expectStockTime: expectStockTime.value, //期望出库时间
        remark: textarea.value,
        warehouseId: route.query.warehouseId,
        deliveryNo: userInfo.value.deliveryNo, // 出库单号
        deliveryProductList: list.value,
        secondmentCustomerId: jdInfo?.customerId || "", //借调客户id
        secondmentCustomerName: jdInfo?.receivingName || "", //借调客户名称
        secondmentCustomerPhone: jdInfo?.receivingMobile || "", //借调客户号码
        secondmentCustomerAddress: jdInfo?.address || "", //借调客户地址
        secondmentCustomerRemark: jdInfo?.secondmentCustomerRemark || "" //借调客户备注
      };
      // console.log(90909090, params);
      createDeliveryOrder(params).then(res => {
        if (res.code === 200) {
          ElMessageBox.confirm("", "", {
            cancelButtonText: "取消",
            confirmButtonText: "前往查看",
            dangerouslyUseHTMLString: true,
            message: "<div class='img'></div><p>订单出库申请创建成功，可前往订单出库申请中查看！</p>",
            customClass: "my-success-messagebox",
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false
          })
            .then(() => {
              console.log("前往出库列表查看");
              router.push({ path: "/procure/outbound" });
            })
            .catch(async () => {
              // 取消
              const info = await createOtherDeliveryOrderInfo();
              userInfo.value = info.data;

              getList();
            });
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//查询详情数据
const getList = () => {
  if (route.query._time) {
    getTempDeliveryProductList({
      code: route.query._time
    }).then(res => {
      if (res.code === 200) {
        list.value = res.data.tempProductInfoList;
        // list.value = [{}, {}, {}];
        detail.value = res.data;

        form.value = {
          receivingName: res.data.receivingName,
          receivingMobile: res.data.receivingMobile,
          receivingAreaIds: res.data.receivingAreaIds ? res.data.receivingAreaIds.split(",").map(Number) : [],
          receivingAddress: res.data.receivingAddress
        };

        for (let item of list.value) {
          item.quantity = 1;
          item.partQuantity = 0;
        }
      }
    });
  }
};
//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
.divider {
  border-bottom: 1px solid #e2e8f0;
  margin: 20px -20px;
}
.procure-outbound-put {
  height: calc(100% - 64px);
  overflow-y: auto;
  padding: 0 20px 64px 20px;
  position: relative;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .info {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    & > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 14px 0;
      border-bottom: 1px solid #e2e8f0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      h3 {
        &.green {
          color: #14c85c;
        }
        &.gray {
          color: #86909c;
        }
        &.orange {
          color: #ff9900;
        }
      }
      .creater {
        color: #1a1a1a;
        font-weight: bold;
      }
    }
  }
  .content {
    height: calc(100% - 75px);
    :deep(.el-aside) {
      flex: 1;
      padding: 20px 20px 20px 0;
      header {
        margin-bottom: 18px;
        .supper {
          flex: 1;
          display: flex;
          align-items: center;
          padding-right: 20px;
          p {
            width: 100%;
            color: #86909c;
            font-size: 18px;
            b {
              color: #3d3d3d;
              font-weight: normal;
            }
          }
          .el-select {
            flex: 1;
          }
        }
        .count {
          display: flex;
          justify-content: space-between;
          padding: 10px 20px;
          background-color: #f6f8fa;
          margin-top: 20px;
          h3 {
            font-size: 16px;
            font-weight: normal;
          }
        }
      }
      .products-list {
        .table-header {
          background-color: #f2f6fc;
          margin-bottom: 10px;
        }
        .table-body {
          .list-item {
            margin-bottom: 10px;
            & > div {
              border: 1px solid #e1e6ed;
              display: flex;
              // align-items: center;
              &:not(:first-of-type) {
                border-left: none;
              }
              &:not(:last-of-type) {
                & > div:not(:last-of-type) {
                  border-right: 1px solid #e1e6ed;
                }
              }
              & > div {
                display: flex;
                align-items: center;
              }
            }
            .col1 {
              & > div {
                display: flex;
              }

              .left {
                img {
                  width: 80px;
                  height: 80px;
                  border-radius: 4px;
                }
              }
              .right {
                padding-left: 18px;
                .name {
                  font-size: 14px;
                  color: #3d3d3d;
                  margin-bottom: 5px;
                }
                p {
                  font-size: 12px;
                  color: #86909c;
                  margin-bottom: 5px;
                }
              }
            }
            .tips {
              display: flex;
              padding: 16px 14px;
              border-top: none;
              border-left: 1px solid #e1e6ed !important;
              p.label {
                width: 38px;
              }
              .el-input {
                flex: 1;
                .el-input__wrapper {
                  background-color: #f2f3f5;
                }
              }
            }
          }
        }
        .table-header,
        .table-body {
          & > div > div:first-of-type {
            display: flex;
            justify-content: space-between;
            & > div {
              padding: 14px 20px;
              &.col1 {
                // width: 45%;
                flex: 1;
              }
              &.col2,
              &.col4,
              &.col7,
              &.col8 {
                width: 80px;
                box-sizing: border-box;
              }
              &.col3 {
                width: 140px;
                box-sizing: border-box;
              }
              &.col5,
              &.col6 {
                width: 125px;
                box-sizing: border-box;
              }
            }
          }
        }
      }
    }
    :deep(.el-main) {
      width: 300px;
      flex: none;
      background-color: #f6f8fa;
      border-left: 1px solid #e2e8f0;
      .ck-time,
      .ps-people {
        p {
          width: 120px;
          margin-bottom: 10px;
        }
        .el-select {
          flex: 1;
        }
      }
      .ps-people {
        & > div {
          display: flex;
          .el-button {
            font-size: 12px;
          }
        }
      }
      .kh-info {
        h3 {
          color: #86909c;
          font-weight: normal;
          margin: 20px 0 16px 0;
        }
        p {
          color: #86909c;
          margin-bottom: 10px;
        }
        b {
          font-weight: normal;
          color: #1a1a1a;
        }
      }
      .sh-info {
        & > p {
          font-size: 16px;
          color: #86909c;
          margin-bottom: 10px;
        }
        .sh-address {
          display: flex;
          justify-content: space-between;
        }
        .el-form-item {
          flex-direction: column;
          span {
            line-height: 20px;
          }
        }
        .el-form-item__label-wrap {
          margin-left: 0 !important;
          .el-form-item__label {
            color: #86909c;
          }
        }
      }
      .ck-tips {
        p.label {
          color: #4e5969;
          margin-bottom: 16px;
        }
      }
    }
  }
  .action-wrap {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
    height: 64px;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  }
}
</style>
